package com.example.menuvirtualclient.adapter;

import java.io.File;
import java.io.InputStream;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.res.ColorStateList;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.Typeface;
import android.graphics.drawable.BitmapDrawable;
import android.os.AsyncTask;
import android.os.Environment;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.LinearLayout.LayoutParams;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.example.menuvirtualclient.FullscreenActivity;
import com.example.menuvirtualclient.R;
import com.example.menuvirtualclient.core.Comment;
import com.example.menuvirtualclient.core.Dish;
import com.example.menuvirtualclient.core.Order;
import com.example.menuvirtualclient.core.OrderDetail;
import com.example.menuvirtualclient.core.Price;
import com.example.menuvirtualclient.rule.CommentRule;
import com.example.menuvirtualclient.rule.DishRule;
import com.example.menuvirtualclient.rule.MenuRule;
import com.example.menuvirtualclient.rule.OrderDetailRule;
import com.example.menuvirtualclient.rule.OrderRule;
import com.example.menuvirtualclient.util.Common;
import com.example.menuvirtualclient.util.RestClient;

public class DishAdapter extends ArrayAdapter<Dish> {
	Context context;
	int layoutResourceId;
	Dish objects[] = null;
	float imageWidth;
	private OrderDetailRule _orderDetailRule;
	private OrderRule _orderRule;
	private MenuRule _menuRule;
	private DishRule _dishRule;
	private Bitmap bm;

	public final void setBm(Bitmap bm) {
		this.bm = bm;
	}

	public DishAdapter(Context context, int layoutResourceId, Dish[] objects) {
		super(context, layoutResourceId, objects);
		// TODO Auto-generated constructor stub
		this.context = context;
		this.layoutResourceId = layoutResourceId;
		this.objects = objects;
		_orderDetailRule = new OrderDetailRule(context);
		_orderRule = new OrderRule(context);
		_menuRule = new MenuRule(context);
		_dishRule = new DishRule(context);
	}

	public DishAdapter(Context context, int layoutResourceId, List<Dish> objects) {
		super(context, layoutResourceId, objects);
		// TODO Auto-generated constructor stub
		this.context = context;
		this.layoutResourceId = layoutResourceId;
		this.objects = objects.toArray(new Dish[objects.size()]);
		_orderDetailRule = new OrderDetailRule(context);
		_orderRule = new OrderRule(context);
		_menuRule = new MenuRule(context);
		_dishRule = new DishRule(context);
	}

	public View getView(int position, View convertView, ViewGroup parent) {
		View row = convertView;
		final ComponentsHolder holder;
		final int cc = position;
		Dish componentsList = objects[cc];
		
		// row = null; // This clears the view, so the rows are well drawn but
		// makes the app much slower
		if (row == null) {
			LayoutInflater inflater = ((Activity) context).getLayoutInflater();
			row = inflater.inflate(layoutResourceId, parent, false);

			holder = new ComponentsHolder();
			holder.id = (TextView) row.findViewById(R.id.id);
			holder.name = (TextView) row.findViewById(R.id.name);
			holder.name_second_half = (TextView) row
					.findViewById(R.id.name_second_half);
			holder.description = (TextView) row.findViewById(R.id.description);
			holder.price = (TextView) row.findViewById(R.id.price);
			holder.size = (TextView) row.findViewById(R.id.size);
			holder.photo = (ImageView) row.findViewById(R.id.photo);
			holder.add = (Button) row.findViewById(R.id.btnAddDish);
			holder.plus = (TextView) row.findViewById(R.id.plus);
			holder.addTo = (TextView) row.findViewById(R.id.agregarA);
			holder.sizesPrices = (RadioGroup) row.findViewById(R.id.sizesPrices);

			row.setTag(holder);
		} else {
			holder = (ComponentsHolder) row.getTag();

			holder.id.setText("");
			holder.name.setText("");
			holder.name_second_half.setText("");
			holder.description.setText("");
			holder.price.setText("");
			holder.size.setText("");
			holder.photo.setVisibility(View.GONE);
			holder.sizesPrices.removeAllViews();
			holder.sizesPrices.removeAllViewsInLayout();
		}

		

		holder.id.setText((String.valueOf(componentsList.getId())));
		if (componentsList.getName().split(" ").length > 1) {
			holder.name.setText(componentsList.getName().split(" ")[0]);
			holder.name_second_half.setText(componentsList.getName().replace(
					componentsList.getName().split(" ")[0], ""));
		} else {
			holder.name.setText(componentsList.getName());
		}
		holder.description.setText(componentsList.getDescription());
		holder.price.setText(String.valueOf(componentsList.getPrice()));
		holder.size.setText(componentsList.getSize());
		String photo = componentsList.getPhoto();

		holder.add.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				OrderDetail orderDetail = new OrderDetail();
				View view = (View) v.getParent();
				int id = Integer.valueOf(((TextView) view.findViewById(R.id.id))
						.getText().toString());

				Order order = new Order();
				Dish dish = new Dish();
				// Menu menu = new Menu();
				try {
					order = FullscreenActivity._order;
					if (order==null) {
						ShowToast("Seleccione una mesa para comenzar.");
						return;
					}
					dish = _dishRule.Get(id);

					// Verifico que tamaño y precio están seleccionados
					RadioGroup rdoGroup = (RadioGroup) ((View) view
							.getParent()).findViewById(R.id.sizesPrices);
					
					int count = holder.sizesPrices.getChildCount();
			        String size = "Normal";
			        for (int i=0;i<count;i++) {
			            View o = holder.sizesPrices.getChildAt(i);
			            if (o instanceof RadioButton && ((RadioButton)o).isChecked()) {
			            	size = ((RadioButton)o).getText().toString().split(" ")[0];
			            	size = (size.equals(""))?"Normal":size;
							dish.setPrice(Double.valueOf(((RadioButton)o).getText()
									.toString().split(" ")[1].replace("$", "")));
			            }
			        }
					

					dish.setSize(size);
				} catch (Exception e1) {
					e1.printStackTrace();
				}

				orderDetail.setId(FullscreenActivity.tempDetailId - 1);
				FullscreenActivity.tempDetailId = FullscreenActivity.tempDetailId - 1;
				orderDetail.setDish(dish);
				orderDetail.setStatus(-1);
				orderDetail.setOrder(order);
				try {
					FullscreenActivity._order.getOrderDetails()
							.add(orderDetail);
					// Salvo el estado de la orden
					_orderRule.saveToTemp(FullscreenActivity._order);
				} catch (Exception e) {
					e.printStackTrace();
				}

				new AddComments(v, orderDetail);

				if (orderDetail.getId() < 0) {
					// Mostrar un toad informando que se grabo el registro
					ShowToast("Se agrego el menú a su orden.");
				} else {
					// mostrar un toad diciendo error
					ShowToast("Error agregando el menú a la orden.");
				}
			}
		});

		row.setOnTouchListener(new OnSwipeTouchListener() {

		});

		holder.addTo.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				Button btnAdd = (Button) ((View) v.getParent())
						.findViewById(R.id.btnAddDish);
				btnAdd.performClick();

			}
		});

		holder.plus.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				Button btnAdd = (Button) ((View) v.getParent())
						.findViewById(R.id.btnAddDish);
				btnAdd.performClick();

			}
		});

		if (!componentsList.getPhoto().equals("")) {
			holder.name.setTextSize(40);
			holder.description.setTextSize(25);

			// File sdcard = Environment.getExternalStorageDirectory();
			File file = new File(Environment.getExternalStorageDirectory()
					+ File.separator + "ImagesMenuVirtual");
			if (file.mkdirs())
				Log.i("mensaje", "se creo el directorio");
			else
				Log.i("mensaje", "el directorio ya existe");

			final String imageKey = componentsList.getPhoto();

			final Bitmap bitmap = getBitmapFromMemCache(imageKey);
			if (bitmap != null) {
				holder.photo.setImageBitmap(bitmap);
				// holder.photo.setTag(componentsList.getImage());
				holder.photo.setVisibility(View.VISIBLE);
			} else {
				new getImage() {
					@Override
					protected void onPostExecute(Bitmap result) {
						if (result != null) {

							holder.photo.setImageBitmap(result);
							holder.photo.setVisibility(View.VISIBLE);
						} else {
							holder.photo.setVisibility(View.GONE);
							holder.photo.setTag("empty");
							int size = ((View) holder.photo.getParent())
									.getHeight();
						}
					}
				}.execute(Common.URL_IMAGES + componentsList.getPhoto());
			}

		} else {
			holder.photo.setVisibility(View.GONE);
			holder.photo.setTag("empty");

		}

		try {

			// Muestro los precios con sus sizes TODO: Cambiar para que tengan
			// mas precios y tamaños ahora está fijado a tres
			List<Price> lstPrices = _dishRule.getPriceByDish(componentsList
					.getId());

			
			int counter = 0;
			for (Price price : lstPrices) {

				String size = "Normal";
				
				counter = counter + 1;
				RadioButton rdoSizePrice = new RadioButton(context);
				
				switch (price.getSize()){
				case 1:
					size = "";
					break;
				case 2:
					size = getSizeName(2);
					break;
				case 3:
					size = getSizeName(3);
					break;	
				}
				
				
				rdoSizePrice.setText(size + " $" + price.getValue() + "  ");
				rdoSizePrice.setTextColor(ColorStateList.valueOf(Color.BLACK));
				rdoSizePrice.setButtonDrawable(R.drawable.btn_radio_holo_light);
				rdoSizePrice.setTypeface(Typeface.create("sans-serif-light", Typeface.NORMAL));
				rdoSizePrice.setTextSize(20);
				holder.sizesPrices.addView(rdoSizePrice);
				
			}
			
			((RadioButton)holder.sizesPrices.getChildAt(0)).setChecked(true);
			

		} catch (Exception e) {
			e.printStackTrace();
		}

		holder.photo.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				RelativeLayout rlDishDetail = (RelativeLayout) ((View) v
						.getParent().getParent().getParent().getParent().getParent())
						.findViewById(R.id.dishDetail);
				View vBlackCourtain = (View) ((View) v.getParent().getParent()
						.getParent().getParent().getParent()).findViewById(R.id.blackCourtain);

//				((TextView) rlDishDetail.findViewById(R.id.disthDetailName))
//						.setText(((TextView) ((View)v.getParent().getParent()).findViewById(R.id.name))
//								.getText());
				((TextView) rlDishDetail.findViewById(R.id.disthDetailName))
				.setText(holder.name.getText());
				((TextView) rlDishDetail
						.findViewById(R.id.disthDetailNameSecond)).setText(holder.name_second_half.getText());
				((TextView) rlDishDetail.findViewById(R.id.disthDetailDescr))
						.setText(holder.description.getText());
				
//				((TextView) rlDishDetail.findViewById(R.id.disthDetailPrice))
//						.setText(((TextView) ((View)v.getParent().getParent()).findViewById(R.id.price))
//								.getText());
				((TextView) rlDishDetail.findViewById(R.id.disthDetailPrice)).setVisibility(View.INVISIBLE);
				
//				((TextView) rlDishDetail.findViewById(R.id.disthDetailSize))
//						.setText(((TextView) ((View)v.getParent().getParent()).findViewById(R.id.size))
//								.getText());
				((TextView) rlDishDetail.findViewById(R.id.disthDetailSize)).setVisibility(View.INVISIBLE);
				

//				((TextView) rlDishDetail.findViewById(R.id.idMenu2))
//						.setText(((TextView) ((View)v.getParent().getParent()).findViewById(R.id.id)).getText());

				((TextView) rlDishDetail.findViewById(R.id.idMenu2))
				.setText(holder.id.getText());
				
				// Log.i("Valor de idMenu2=", ((TextView)
				// v.findViewById(R.id.id)).getText().toString());

				if (((ImageView) ((View)v.getParent().getParent()).findViewById(R.id.photo)).getVisibility() == View.VISIBLE) {
					Bitmap bmSrc1 = ((BitmapDrawable) ((ImageView) v
							.findViewById(R.id.photo)).getDrawable())
							.getBitmap();
					Bitmap bmSrc2 = bmSrc1.copy(bmSrc1.getConfig(), true);
					((ImageView) rlDishDetail
							.findViewById(R.id.dishDetailPhoto))
							.setImageBitmap(bmSrc2);
				} else {
					((ImageView) rlDishDetail
							.findViewById(R.id.dishDetailPhoto))
							.setImageBitmap(null);
				}
				
				// Verifico que tamaño y precio están seleccionados
				RadioGroup llBtnPrices = (RadioGroup) rlDishDetail.findViewById(R.id.llBtnPrice);
				llBtnPrices.removeAllViews();
				
				int count = holder.sizesPrices.getChildCount();
		        String size = "Normal";
		        for (int i=0;i<count;i++) {
		            View o = holder.sizesPrices.getChildAt(i);
		            if (o instanceof RadioButton) {
		            	RadioButton rdo = new RadioButton(context);
		            	rdo.setText(((RadioButton)o).getText());

		            	
		            	rdo.setTextColor(ColorStateList.valueOf(Color.BLACK));
		            	rdo.setButtonDrawable(R.drawable.btn_radio_holo_light);
		            	rdo.setTypeface(Typeface.create("sans-serif-light", Typeface.NORMAL));
		            	rdo.setTextSize(20);
		            	
		            	llBtnPrices.addView(rdo);
		            	// El set Checked tiene que ir después del addview
		            	if(((RadioButton)o).isChecked()){
		            		rdo.setChecked(true);
		            	}
		            }
		        }
				
				
		        
				
//				int count = holder.sizesPrices.getChildCount();
//		        String size = "Normal";
//		        for (int i=0;i<count;i++) {
//		            View o = holder.sizesPrices.getChildAt(i);
//		            if (o instanceof RadioButton && ((RadioButton)o).isChecked()) {
//		            	size = ((RadioButton)o).getText().toString().split(" ")[0];
//		            	size = (size.equals(""))?"Normal":size;
//						dish.setPrice(Double.valueOf(((RadioButton)o).getText()
//								.toString().split(" ")[1].replace("$", "")));
//		            }
//		        }

				vBlackCourtain.setVisibility(View.VISIBLE);

				rlDishDetail.setVisibility(View.VISIBLE);
				rlDishDetail.animate().alpha(1).start();

			}
		});


		return row;
	}

	private void ShowToast(String message) {
		Toast toast = Toast.makeText(context, message, Toast.LENGTH_SHORT);
		toast.show();
	}

	static class ComponentsHolder {
		TextView id;
		TextView name;
		TextView name_second_half;
		TextView description;
		TextView price;
		TextView size;
		ImageView photo;
		ImageView magnifier;
		Button add;
		TextView plus;
		TextView addTo;
		RadioGroup sizesPrices;
	}

	public class AddComments extends Activity {
		
		
		public AddComments(View view, OrderDetail orderDetail) {
			addComments(view, orderDetail);
		}

		public void addComments(View view, OrderDetail orderDetail) {
			AlertDialog.Builder builder = new AlertDialog.Builder(
					view.getContext());
			LayoutInflater inflater = (LayoutInflater) view.getContext()
					.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
			final List<Integer> intList = new ArrayList<Integer>();
			final int dishId;
			final int detailId;

			builder.setView(inflater.inflate(R.layout.layout_order_comments,
					null));
			FullscreenActivity.dialog = builder.create();

			FullscreenActivity.dialog.show();

			// final TextView tvCommentsList = (TextView) ((RelativeLayout) view
			// .getParent()).findViewById(R.id.commentsList);

			LinearLayout ln = (LinearLayout) FullscreenActivity.dialog
					.findViewById(R.id.listCommentsDialog);

			final EditText etComment = (EditText)ln.findViewById(R.id.etComment);
			
			LinearLayout lh = new LinearLayout(view.getContext());
			lh.setOrientation(0);
			Button btnCancelar = new Button(view.getContext());
			btnCancelar.setText("Cancelar");
			btnCancelar.setOnClickListener(new View.OnClickListener() {

				@Override
				public void onClick(View v) {
					FullscreenActivity.dialog.dismiss();
				}
			});
			
			// Creo el edit de comentarios
//			final EditText etComment = new EditText(view.getContext());
			
			//Agrego los tipos de plato - entra principal o postres
			RadioGroup rgrDetailTypes = new RadioGroup(view.getContext());
			rgrDetailTypes.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT,  LayoutParams.WRAP_CONTENT));
			rgrDetailTypes.setOrientation(0);
			
			final RadioButton rdoStarter = new RadioButton(view.getContext());
			rdoStarter.setText("Entrada");
			rdoStarter.setTextColor(view.getContext().getResources().getColor(R.color.AlmostBlack));
			rdoStarter.setButtonDrawable(R.drawable.btn_radio_holo_light);
			rdoStarter.setTypeface(Typeface.create("sans-serif-light", Typeface.NORMAL));
			rdoStarter.setTextSize(20);
        	
			
			final RadioButton rdoMain = new RadioButton(view.getContext());
			rdoMain.setText("P. Principal");
			rdoMain.setTextColor(view.getContext().getResources().getColor(R.color.AlmostBlack));
			rdoMain.setButtonDrawable(R.drawable.btn_radio_holo_light);
			rdoMain.setTypeface(Typeface.create("sans-serif-light", Typeface.NORMAL));
			rdoMain.setTextSize(20);
			
			final RadioButton rdoDessert = new RadioButton(view.getContext());
			rdoDessert.setText("Postre");
			rdoDessert.setTextColor(view.getContext().getResources().getColor(R.color.AlmostBlack));
			rdoDessert.setButtonDrawable(R.drawable.btn_radio_holo_light);
			rdoDessert.setTypeface(Typeface.create("sans-serif-light", Typeface.NORMAL));
			rdoDessert.setTextSize(20);
			
			rgrDetailTypes.addView(rdoDessert);
			rgrDetailTypes.addView(rdoMain);
			rgrDetailTypes.addView(rdoStarter);
			
			
			
			
			Button btnAceptar = new Button(view.getContext());
			btnAceptar.setText("Aceptar");
			
			// Datos que se guardan al momento de elegir acompañamientos
			btnAceptar.setOnClickListener(new View.OnClickListener() {

				@Override
				public void onClick(View v) {
					List<Comment> cos = new ArrayList<Comment>();
					CommentRule _commentRule = new CommentRule(v.getContext());
					// tvCommentsList.setText("");
					for (int id : intList) {
						Comment co = new Comment();
						// co.setId(id);
						// cos.add(co);
						try {
							co = _commentRule.Get(id);
							cos.add(co);
							// tvCommentsList.setText(tvCommentsList.getText()
							// .toString() + " " + co.getDescription());

						} catch (Exception e) {
							e.printStackTrace();
						}
					}

					for (OrderDetail od : FullscreenActivity._order
							.getOrderDetails()) {
						if (od.getId() == FullscreenActivity.idDetail) {
							od.setComments(cos);
							od.setComment(etComment.getText().toString());
							if(rdoDessert.isChecked())od.setDetail_type(2);
							if(rdoMain.isChecked())od.setDetail_type(1);
							if(rdoStarter.isChecked())od.setDetail_type(0);
						}
					}

					// Salvo el estado de la orden
					FullscreenActivity._presenter
							.saveToTemp(FullscreenActivity._order);

					intList.clear();
					FullscreenActivity.dialog.cancel();
				}
			});

			// TextView tvIdDish = (TextView) ((RelativeLayout)
			// view.getParent())
			// .findViewById(R.id.idDish);
			// dishId = Integer.valueOf(tvIdDish.getText().toString());
			// TextView tvIdDetail = (TextView) ((RelativeLayout)
			// view.getParent())
			// .findViewById(R.id.idMenu);

			dishId = orderDetail.getDish().getId();

			FullscreenActivity.idDetail = Integer.valueOf(orderDetail.getId());
			// Busco el comment list del plato para despu�s actualizar el
			// detalle

			List<OrderDetail> lstDetails = FullscreenActivity._order
					.getOrderDetails();

			List<Comment> lstComments = FullscreenActivity._presenter
					.GetCommentByDish(dishId);


			ln.addView(rgrDetailTypes);
			if(orderDetail.getDish().getType()==0){
				rdoMain.setChecked(true);
			}else if(orderDetail.getDish().getType()==1){
				rdoStarter.setChecked(true);
			}else if(orderDetail.getDish().getType()==2){
				rdoDessert.setChecked(true);
			}
			
			for (Comment comment : lstComments) {
				CheckBox ch = new CheckBox(view.getContext());
				for (OrderDetail od : lstDetails) {
					if (od.getComments() != null
							&& od.getId() == FullscreenActivity.idDetail) {
						for (Comment c : od.getComments()) {
							if (c != null && comment.getId() == c.getId()) {
//								ch.setChecked(true);
//								intList.add(c.getId());
								// tvCommentsList.setText(tvCommentsList.getText().toString()+c.getDescription());
							}
						}
					}
				}
				ch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {

					@Override
					public void onCheckedChanged(CompoundButton buttonView,
							boolean isChecked) {
						// TODO Auto-generated method stub
						Log.i("onCheckedChanged", "=========================");
						Log.i("buttonView.getId()",
								Integer.toString(buttonView.getId()));
						if (isChecked) {
							intList.add(buttonView.getId());
						} else {
							// C�digo original - Error: Indice fuera de rango
							// Invalid index 2, size is 2
							// intList.remove(buttonView.getId());
							// ----------------------------------------
							for (int i = 0; i < intList.size(); i++)
								if (intList.get(i) == buttonView.getId()) {
									intList.remove(i);
								}
						}
					}
				});

				ch.setTextAppearance(view.getContext(), R.style.AppTitlesPopUp);
				ch.setText(comment.getDescription());
				ch.setId(comment.getId());
				ln.addView(ch);
			}
			
//			etComment.setHint("Comentarios");
//			etComment.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT,
//					LayoutParams.WRAP_CONTENT));
//			ln.addView(etComment);
			
			lh.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT,
					LayoutParams.WRAP_CONTENT));
			lh.setWeightSum(2);

			LinearLayout.LayoutParams lParams = (LinearLayout.LayoutParams) lh
					.getLayoutParams(); // or create new LayoutParams...

			lParams.weight = 1f;

			btnAceptar.setLayoutParams(lParams);
			btnCancelar.setLayoutParams(lParams);

			lh.addView(btnAceptar);
			lh.addView(btnCancelar);

			ln.addView(lh);

			
			
//			if (lstComments.size() == 0) {
//				FullscreenActivity.dialog.dismiss();
//			}
		}
	}

	private String getSizeName(int id) {
		switch (id) {
		case 1:
			return "Normal";
		case 2:
			return "Chica";
		case 3:
			return "Grande";
		}
		return "Normal";
	}

	// resize the image proportionately so it fits the entire space
	@SuppressWarnings("unused")
	private void setImageBitmap(Integer item, ImageView imageView) {
		Bitmap bitmap = BitmapFactory.decodeResource(getContext()
				.getResources(), item);
		float i = ((float) imageWidth) / ((float) bitmap.getWidth());
		float imageHeight = i * (bitmap.getHeight());
		FrameLayout.LayoutParams params = (FrameLayout.LayoutParams) imageView
				.getLayoutParams();
		params.height = (int) imageHeight;
		params.width = (int) imageWidth;
		imageView.setLayoutParams(params);
		imageView.setImageResource(item);
	}

	public static float convertDpToPixel(float dp, Context context) {
		Resources resources = context.getResources();
		DisplayMetrics metrics = resources.getDisplayMetrics();
		float px = dp * (metrics.densityDpi / 160f);
		return px;
	}

	public void addBitmapToMemoryCache(String key, Bitmap bitmap) {
		if (getBitmapFromMemCache(key) == null) {
			FullscreenActivity.mMemoryCache.put(key, bitmap);
		}
	}

	public final Bitmap getBitmapFromMemCache(String key) {
		return FullscreenActivity.mMemoryCache.get(key);
	}

	private class getImage extends AsyncTask<String, String, Bitmap> {
		RestClient client;
		Bitmap photo;

		protected void onPreExecute() {
			// Mostramos el di�logo antes de comenzar
		}

		protected Bitmap doInBackground(String... urls) {

			// http://localhost:1313/menuvirtualws/services/OperatorClass/saveDishToOrder?idDish=0&idOrder=0&idTable=0&idWaiter=0&time=1240&comments=hola
			// client = new RestClient(urls[0]);
			Bitmap b = null;
			try {
				// client.Execute(RequestMethod.GET);

				b = BitmapFactory.decodeStream((InputStream) new URL(urls[0])
						.getContent());

				addBitmapToMemoryCache(urls[0].split("/")[5], b);
			} catch (Exception e) {
				e.printStackTrace();
			}

			// Bitmap response = client.getResponse();
			// publishProgress(response);
			return b;
		}

		protected void onProgressUpdate(String... valores) {
			// ((TextView)findViewById(R.id.texto)).setText(valores[0].toString());

		}

		protected void onPostExecute(Bitmap img) {
			if (img != null) {
				photo = img;
			}
		}
	}

}
